<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        left-icon="manager"
        v-model="userName"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        left-icon="more"
        v-model="userPwd"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          // 书写对应的正则
          { pattern: /[0-9|a-z|A-Z]{6,10}/, message: '请输入正确的密码' },
          { required: true, message: '请填写密码' },
        ]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script>
import { Toast } from "vant";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { userLogin } from "../../api/user";
import { useStore } from "vuex";
export default {
  setup() {
    const router = useRouter();
    const store = useStore();
    const userName = ref("");
    const userPwd = ref("");
    const onSubmit = async (values) => {
      let res = await userLogin({
        userName: userName.value,
        userPwd: userPwd.value,
      });
      if (res.data.code === 0) {
        store.commit("setUser", res.data);
        router.push({
          path: "/person", //可以存储状态
        });
      } else {
        Toast.fail("用户名或密码错误");
      }
    };

    return {
      userName,
      userPwd,
      onSubmit,
    };
  },
};
</script>

<style>
</style>